package com.example.onlinemonitoring.comCenter;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Gispdhistory;
import com.example.onlinemonitoring.model.Gispdsensor;
import com.example.onlinemonitoring.serviceImpl.GispdsensorServiceImpl;
import org.springframework.context.annotation.Scope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 济钢的开关柜局放
 */
@Service("scpdjgCom")
@Scope("prototype")
public class ScpdjgCom extends CommPortManager {
    @Autowired
    private GispdsensorServiceImpl gispdserviceimpl;
    String recvmsg[] = new String[2];

    public void ClearCache() {
        for (int i = 0; i < recvmsg.length; i++) {
            recvmsg[i] = "";
        }
    }

    @Override
    public void receiveDatas(String str) {
        setText(str);
        if (!str.substring(2, 4).equals("03") || currcmd >= 2) {
            return;
        }
        String addrstr = str.substring(0, 2);
        Integer addrint = parsePHex4(addrstr);
        reSend[addrint] = 0;
        recvmsg[currcmd] = str.substring(6, str.length() - 4);
        if (currcmd == 1 && !recvmsg[0].isEmpty() && !recvmsg[1].isEmpty()) {
            String pdmsg = recvmsg[0];
            String pdvmsg = recvmsg[1];
            Gispdsensor gispdsensor = new Gispdsensor();
            gispdsensor.setStationid(ad.getStationid());
            gispdsensor.setDevicegroup(ad.getDevicegroup());
            List<Gispdsensor> list = gispdserviceimpl.getLists(gispdsensor);
            int pdindex = 0, pdvindex = 0;
            for (Gispdsensor gis : list) {

                try {
                    gispdsensor.setLastdischargeamount(parseHex4(pdmsg.substring(pdindex, pdindex + 4)) * 1f);
                    pdindex += 4;
                    gispdsensor.setLastrst((long) parsePHex4(pdvmsg.substring(pdvindex, pdvindex + 4)));
                    pdvindex += 4;
                } catch (Exception e) {
                    break;
                }
                gispdsensor.setDeviceaddr(gis.getDeviceaddr());
                gispdsensor.setLastdatatime(new Date());
                gispdsensor.setLastcommunicationstatus(0);
                setText("局放设备返回数据： 站点号：1 监测点" + gis.getDeviceaddr());
                setText("放电量：" + gispdsensor.getLastdischargeamount() + "dB");
                setText("放电频次：" + gispdsensor.getLastrst() + "次/s");
                AddAndUpdate(gis, gispdsensor);
            }
            addrindex++;
        }
    }

    private void AddAndUpdate(Gispdsensor record, Gispdsensor gispdsensor) {
        int alarmLevel = 0;// 报警等级
        String alarmMessage = "";// 报警消息
        alarmLevel = GetAlarmStatus(isnull(gispdsensor.getLastdischargeamount()),
                isnull(record.getDischargeamountalarm()),
                isnull(record.getDischargeamountalarm()), isnull(record.getDischargeamountwarning()),
                isnull(record.getDischargeamountwarning()),
                isnull(record.getLastalarmlevel()), true, "放电量", record.getDevicegroup(), record.getDeviceaddr(),
                record.getPointname());
        alarmMessage += GetAlarmMessage(alarmLevel, "放电量");
        gispdsensor.setLastalarmlevel(alarmLevel);
        gispdsensor.setLastalarmmessage(alarmMessage);
        gispdsensor.setLastcommunicationstatus(0);
        gispdsensor.setLasthisdatatime(addHistory(record));
        if (gispdserviceimpl.Update(gispdsensor, false) == 0) {
            setText("更新实时数据失败，请检查数据库连接");
        }
    }

    private Date addHistory(Gispdsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Gispdsensor sensor) {
        Gispdhistory his = new Gispdhistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setPointname(sensor.getPointname());
        his.setHavesignal(sensor.getLasthavesignal());
        his.setSignalpower(sensor.getLastsignalpower());
        his.setDischargeamount(sensor.getLastdischargeamount());
        his.setDischargetype(sensor.getLastdischargetype());
        his.setRst(sensor.getLastrst());
        his.setTot(sensor.getLasttot());
        his.setDatatime(sensor.getLastdatatime());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setMemo(sensor.getMemo());
        his.setInuse(sensor.getInuse());
        his.setStyle(sensor.getStyle());
        gispdserviceimpl.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        String cmd[] = new String[2];
        cmd[0] = "0103238D002B";// 放电频次
        cmd[1] = "01032329002B";// 放电量
        checkType = "crc16";
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        int timeoutsp = (int) Math.round(Appdevice.getTimeoutsp() * 1000);
        timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            rlock.lock();
            try {
                if (isrun) {
                    if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                        addrindex = Appdevice.getAddrmin();
                    currcmd = 0;
                    for (int i = 0; i < cmd.length; i++) {
                        currcmd = i;
                        if (currcmd == 0) {
                            ClearCache();
                        }
                        cstr = String.format(cmd[currcmd], String.format("%02X", addrindex));
                        cstr = cstr + CRC16.calcCrc16(cstr);
                        Send(cstr);
                        //sendCondition.await(timeoutsp, TimeUnit.MILLISECONDS);
                        //currcmd++;
                    }

                    if (reSend[addrindex] > 3) {
                        gispdserviceimpl.UpdateStatus(ad, addrindex, 1);
                        reSend[addrindex] = 0;
                        addrindex++;
                    }
                    reSend[addrindex]++;
                } else if (rescode != 0) {
                    setText(resmsg[rescode]);
                }
            } catch (Exception e) {
                // TODO: handle exception
            } finally {
                rlock.unlock();
            }
        }
    }
}
